/**
 * @author Chris Fraser, Jean-Luc Richard
 */

import java.io.*;
import java.util.Collection;
import java.util.Scanner;

public class PlayerHistory
{
	public static final File DATA_FILE = new File("history.txt");
	private Collection<Player> players;
	private Player[] currentPlayers;
	
	public PlayerHistory()
	{
		currentPlayers = new Player[2];
		this.readData();
	}
	
	/**
	 * Method the data in from the file
	 */
	private void readData()
	{
		try 
		{
			Scanner sc = new Scanner(DATA_FILE);
			while (sc.hasNext())
			{
				Player player = new Player(sc.next());
				players.add(player);
				player = null;
			}
		} 
		catch (FileNotFoundException e) 
		{
			Logger.error("File not found");
		}
	}
	
	/**
	 * Method to update the data in the file
	 */
	public void writeData()
	{		
		//Empty the file
		try
		{
			FileOutputStream fos = new FileOutputStream(DATA_FILE);
			fos.write(new String().getBytes());
			fos.close();
		}
		
		catch (Exception e)
		{
			Logger.error("Error emptying the file.");
		}
		
		//Write out to the file	
		try 
		{
			FileWriter fw = new FileWriter(DATA_FILE);
			BufferedWriter out = new BufferedWriter(fw);
			for (Player player : players)
			{
				out.write(player.getName() + ", " + player.getRecord());
			}
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public String addPlayer(String protIn)
	{
		Player temp = new Player(protIn);
		for (Player player : players)
		{
			if (temp.getName().equalsIgnoreCase(player.getName()))
			{
				return "err,Duplicate User Name";
			}
		}
		
		players.add(new Player(protIn));
		try
		{
			this.currentPlayers[0].getName().isEmpty();
		}
		catch (NullPointerException npe)
		{
			this.currentPlayers[0] = new Player(protIn);
			return "ack";
		}
		
		this.currentPlayers[1] = new Player(protIn);
		return "ack";
	}
	
	public String checkPlayer(String protIn)
	{
		Player temp = new Player(protIn);
		String returnMessage = "err,Unknown User";
		
		for (Player player : players)
		{
			if (temp.getName().equalsIgnoreCase(player.getName()))
			{
				returnMessage = "ack";
				break;
			}
		}
		
		if (returnMessage.equalsIgnoreCase("ack"))
		{
			try
			{
				this.currentPlayers[0].getName().isEmpty();
			}
			catch (NullPointerException npe)
			{
				this.currentPlayers[0] = new Player(protIn);
				return returnMessage;
			}
			
			this.currentPlayers[1] = new Player(protIn);
		}
		
		return returnMessage;
	}
	
	public Player[] getPlayers()
	{
		return this.currentPlayers;
	}

}
